<?php

namespace App\Http\Controllers;
use App\Post;
use App\Comment;
use App\Zan;
use Illuminate\Http\Request;

class PostsController extends Controller
{
    public function index()
    {
        $date = new Post();
        $data = Post::orderBy('created_at','desc')->withCount(['comments','zans'])->paginate(6);
        return view('home.index',compact('data'));
    }

    public function cate(Post $post)
    {
        //预加载模型
        $post->load('comments');
        return view('home.cate',compact('post'));
    }

    /**
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * @throws \Exception
     */
    public function del(Post $post)
    {
        $this->authorize('del',$post);
        $post->delete();
        return redirect('posts');
    }
    public function xie()
    {

        $user_id = \Auth::id();
        $data = array_merge(request(['title','content']),compact('user_id'));
        $pram = Post::create($data);
        return redirect('/posts');
    }
    public function create()
    {

        return view('home.create');
    }



    public function edit(Post $post)
    {

        return view('home.up',compact('post'));

    }

    public function update(Post $post)
    {
        $this->authorize('update',$post);
        $post->title = request('title');
        $post->content = request('content');
        $post->save();
        return redirect("/posts/{$post->id}");
    }
    //提交评论
    public function comment(Post $post)
    {
        $this->validate(request(),[
           'content'=>'required|min:3',
        ]);
        $comment = new Comment();
        $comment->user_id = \Auth::id();
        $comment->content = request('content') ;
        $post->comments()->save($comment);
        return back();
    }
//点赞模块
    public function zan(Post $post)
    {
        $param=[
            'user_id' => \Auth::id(),
            'post_id' => $post->id,
        ];
        zan::FirstOrCreate($param);
        return back();

    }
//取消点赞
    public function unzan(Post $post)
    {
        $post->zan(\Auth::id())->delete();
        return back();
    }
//搜索
    public function search()
    {
        //验证
//        $this->validate(request(),[
//            'query'=>'required'
//        ]);
        //逻辑
        $query = \request('query');
        $posts = Post::search($query)->paginate(2);
        return view('search.index',compact('posts','query'));
    }
}
